import 'package:flutter/material.dart';

/**
 * 交织动画
 */
class StaggerRoute extends StatefulWidget {
  const StaggerRoute({super.key});

  @override
  State<StaggerRoute> createState() => _StaggerRouteState();
}

class _StaggerRouteState extends State<StaggerRoute>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();
    this._controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
      reverseDuration: Duration(seconds: 1),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ElevatedButton(
          onPressed: () async {
            try {
              await _controller.forward().orCancel;
              await _controller.reverse().orCancel;
            } on TickerCanceled {
              print('ticker canceled');
            } catch (e) {}
          },
          child: Text('start animated'),
        ),
        Container(
          height: 300,
          width: 300,
          decoration: BoxDecoration(
            color: Colors.grey.withOpacity(0.1),
            border: Border.all(
              color: Colors.black.withOpacity(0.5),
            ),
          ),
          alignment: Alignment.bottomLeft,
          child: StaggerAnimation(controller: _controller),
        )
      ],
    );
  }
}

class StaggerAnimation extends StatelessWidget {
  StaggerAnimation({Key? key, required this.controller}) : super(key: key) {
    height = Tween<double>(begin: 0.0, end: 260).animate(CurvedAnimation(
        parent: controller, curve: Interval(0.0, 0.6, curve: Curves.ease)));
    color = ColorTween(begin: Colors.blue, end: Colors.red).animate(
        CurvedAnimation(
            parent: controller, curve: Interval(0.0, 0.6, curve: Curves.ease)));
    margin = Tween<EdgeInsets>(
            begin: EdgeInsets.all(0), end: EdgeInsets.only(top: 200, left: 200))
        .animate(CurvedAnimation(
            parent: controller, curve: Interval(0.6, 1.0, curve: Curves.ease)));
  }
  late final AnimationController controller;
  late final Animation<double> height;
  late final Animation<Color?> color;
  late final Animation<EdgeInsets> margin;

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
        animation: controller,
        builder: (context, child) {
          return Container(
            width: 50,
            height: height.value,
            color: color.value,
            margin: margin.value,
          );
        });
  }
}
